const router = require('express').Router();

const { $request } = require('../plugin/request'),
      { baseUrl } = require('../config/api.conf');

/*
* 首页 index.ejs
* */
router.get('/', (req, res, next) => {

    // 所有职位
    let allPost = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/sysPosition/selectAllSysPosition'
    });

    // 最新职位
    let newPost = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/userCenter/listNewestPosition',
        data: {
            pageNo: 1,
            pageSize: 9
        }
    });
    res.originalUrl = req.originalUrl;
    Promise.all([allPost, newPost])
           .finally(data => {
               res.allPost = res.newPost = [];
               const all_post = JSON.parse(data[0] || '{}'),
                     new_post = JSON.parse(data[1] || '{}');
               if(all_post.message === 'success'){
                   res.allPost = all_post.data || [];
               }
               if(new_post.message === 'success'){
                   res.newPost = (new_post.data && new_post.data.results) || [];
               }
               res.render('index.ejs', {
                   title: '语聘 - 专注语言服务职业机会（找全/兼职、实习等语言类工作机会，找语言类专业人才）',
                   resData: res,
                   layout: 'shared/layout'
               })
           })
});

/*
* 职位 post / index.ejs
* */
router.get('/post', (req, res, next) => {

    // 语言
    let language = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/rm/language/listAll'
    });
    // 职位类型
    let allPost = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/sysPosition/selectAllSysPosition'
    });
    Promise.all([language, allPost])
           .finally(data => {
               res.allLanguage = res.allPost = [];
               const _language = JSON.parse(data[0] || '{}'),
                     _allPost = JSON.parse(data[1] || '{}');
               if(_language.message === 'success'){
                   res.allLanguage = _language.data || [];
               }
               if(_allPost.message === 'success'){
                   res.allPost = _allPost.data || [];
               }
               res.render('post/index.ejs', {
                   title: '语聘 - 职位列表 - 专注语言服务职业机会（找全/兼职、实习等语言类工作机会，找语言类专业人才）',
                   resData: res,
                   layout: 'shared/layout'
               })
           })
});

// 职位详情 post / detail.ejs
router.get('/post/:id', (req, res, next) => {

    let { id } = req.params,
        TOKEN = req.cookies['USER_TOKEN'];

    if(id.includes('.html')){
        id = id.split('.html')[0]
    }

    // 该职位是否已投递简历
    let isDeliver = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/userCenter/checkCurrentPosDeliverStatus',
        data: {
            positionCode: id
        },
        headers: {
            "Authorization": TOKEN ? "bearer " + TOKEN : ''
        }
    });

    // 该职位是否已收藏
    let isCollect = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/userCenter/judgePositionCollection',
        data: {
            positionCode: id
        },
        headers: {
            "Authorization": TOKEN ? "bearer " + TOKEN : ''
        }
    });

    // 职位详情
    let postDetail = $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/userCenter/positionDetail',
        data: {
            positionCode: id
        },
        headers: {
            "Authorization": TOKEN ? "bearer " + TOKEN : ''
        }
    });

    Promise.all([isDeliver, isCollect, postDetail])
           .finally(data => {
                res.isDeliver = res.isCollect = false;
                res.postDetail = res.companyDetail = {};
                const _isDeliver = JSON.parse(data[0] || '{}'),
                    _isCollect = JSON.parse(data[1] || '{}'),
                    _postDetail = JSON.parse(data[2] || '{}');
                if(_isDeliver.message === 'success'){
                    res.isDeliver = _isDeliver.data;
                }
                if(_isCollect.message === 'success'){
                    res.isCollect = _isCollect.data;
                }
                if(_postDetail.message === 'success'){
                    res.postDetail = _postDetail.data;
                    res.companyDetail = _postDetail.data && _postDetail.data.company || {};
                }
                let title = '职位详情';
                if(res.postDetail.positionTitle){
                    title = res.postDetail.positionTitle + ' - ' + res.postDetail.companyName + ' - ' + res.postDetail.detailedAddress
                }

                res.render('post/detail.ejs', {
                    title: title,
                    resData: res,
                    layout: 'shared/layout'
                })
           })
});

// 公司详情 post / company.ejs
router.get('/post/company/:id', (req, res, next) => {

    let { id } = req.params;

    if(id.includes('.html')){
        id = id.split('.html')[0]
    }

    $request({
        method: 'get',
        baseUrl: baseUrl,
        url: '/job/userCenter/companyPublishPositionDetail',
        data: {
            pageNo: 1,
            pageSize: 1,
            companyId: id
        }
    }).finally(data => {
        data = JSON.parse(data);
        res.detail = {};
        res.total = 0;
        if(data.message === 'success' && data.data){
            res.total = data.data.totalCount;
            res.detail = (data.data.results && data.data.results[0]) || {};
            res.detail.companyId = id;
        }

        let title = '公司详情';
        if(res.detail.companyName){
            title = res.detail.companyName + ' - ' + res.total + '个在招职位'  + ' - ' + res.detail.detailedAddress
        }

        res.render('post/company.ejs', {
            title: title,
            resData: res,
            layout: 'shared/layout'
        })
    })

});

module.exports = router;